// 引入axios
import axios, { AxiosRequestConfig, Method } from 'axios';

import { ElNotification, ElMessageBox, ElMessage, ElLoading } from 'element-plus'

// 定义接口
interface PendingType {
    url?: string;
    method?: Method;
    params: any;
    data: any;
    cancel: Function;
}

// 取消重复请求
const pending: Array<PendingType> = [];

const CancelToken = axios.CancelToken;

// 移除重复请求
const removePending = (config: AxiosRequestConfig) => {
    for (const key in pending) {
        const item: number = +key;
        const list: PendingType = pending[key];
        // 当前请求在数组中存在时执行函数体
        if (list.url === config.url && list.method === config.method && JSON.stringify(list.params) === JSON.stringify(config.params) && JSON.stringify(list.data) === JSON.stringify(config.data)) {
            // 执行取消操作
            list.cancel('操作太频繁，请稍后再试');
            // 从数组中移除记录
            pending.splice(item, 1);
        }
    }
};

let loadingInstance: any;

import store from '@/store/index'

//  http  请求头封装
// axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8';
axios.defaults.withCredentials = true;  //允许axios请求携带cookie等凭证

// 创建axios实例
const serviceConfig = axios.create({
    // axios中请求配置有baseURL选项，表示请求URL公共部分
    baseURL: process.env.VUE_APP_MOCK == "true" ? "" : process.env.VUE_APP_BASE_API, // url = base url + request url
    // 超时
    timeout: 50000,
})

// request拦截器
serviceConfig.interceptors.request.use((config: AxiosRequestConfig) => {
    loadingInstance = ElLoading.service({
        text: '加载中',
        background: 'rgba(0, 0, 0, 0.3)'
    });
    removePending(config);
    config.cancelToken = new CancelToken((c) => {
        pending.push({ url: config.url, method: config.method, params: config.params, data: config.data, cancel: c });
    });
    return config
}, error => {
    loadingInstance.close();
    return Promise.reject(error)
})

// response拦截器
serviceConfig.interceptors.response.use(response => {
    loadingInstance.close();
    removePending(response.config);
    const res = response.data;
    const code = res.code || 2000;
    if (code === 4001) {
        ElMessageBox.alert('您登录已过期，请前往登录后再进行此操作！', '系统提示', {
            confirmButtonText: '确定',
            callback: function () {
                store.dispatch('UserLogout');
            }
        });
    } else if (code === 5000) {
        ElMessage({
            message: res.message ? res.message : '系统异常',
            type: 'error'
        })
        return Promise.reject(new Error(res.message ? res.message : '系统异常'))
    } else if (code !== 2000) {
        ElNotification({
            title: res.message ? res.message : '系统异常',
            type: 'error'
        })
        return Promise.reject('error')
    } else {
        return res.data
    }
},
    error => {
        loadingInstance.close();
        const { message } = error;
        ElMessageBox.alert(message, "系统提示");
        return Promise.reject(error)
    }
)

export default serviceConfig